package com.example.take_out_dish.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.take_out_dish.common.Result;


import com.example.take_out_dish.config.JwtConfig;
import com.example.take_out_dish.dto.CAT;
import com.example.take_out_dish.dto.DCF;
import com.example.take_out_dish.entity.Category;
import com.example.take_out_dish.entity.Dish;
import com.example.take_out_dish.entity.DishFlavor;
import com.example.take_out_dish.entity.SetmealDish;
import com.example.take_out_dish.exceptions.BusinessException;
import com.example.take_out_dish.exceptions.enumetation.ResponseEnum;
import com.example.take_out_dish.service.CategoryService;
import com.example.take_out_dish.service.DishFlavorService;
import com.example.take_out_dish.service.DishService;

import com.example.take_out_dish.utils.JwtUtils;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.websocket.server.PathParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author wuyunbin
 * @since 2024-07-01
 */
@RestController
@Slf4j
@RequestMapping("/dish")
@Tag(name = "菜品管理")
public class DishController {
    @Resource
    private DishService dishService;
    // 查询列表
    @Resource
    private DishFlavorService dishFlavorService;
    @Resource
    private CategoryService categoryService;

    @Resource
    HttpServletRequest request;

    @Resource
    JwtConfig jwtConfig;

    @GetMapping("page")
    public Result<IPage<DCF>> page(int page, int pageSize, String name, String categoryId, Integer status){
        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<>();
        wrapper.ne(Dish::getIsDeleted,1);
        if (status != null) {
            wrapper.eq(Dish::getStatus,status);
        }
        wrapper.like(StrUtil.isNotBlank(name), Dish::getName, name);
        wrapper.eq(StrUtil.isNotBlank(categoryId),Dish::getCategoryId,categoryId);
        log.info("categoryId:{}",categoryId);
        IPage<Dish> dishPage = dishService.page(new Page<>(page, pageSize),wrapper);

        IPage<DCF> dcfPage = new Page<>(dishPage.getCurrent(), dishPage.getSize(), dishPage.getTotal());
        dcfPage.setRecords(new ArrayList<>());
        List<Dish> records = dishPage.getRecords();
        for (Dish record : records) {
            DCF dcf = new DCF();

            // 获取Category名称
            LambdaQueryWrapper<Category> cgWrapper = new LambdaQueryWrapper<>();
            cgWrapper.eq(Category::getId, record.getCategoryId());
            Category category = categoryService.getOne(cgWrapper);
            dcf.setCategoryname(category.getName());

            // 获取DishFlavor名称
            LambdaQueryWrapper<DishFlavor> dfWrapper = new LambdaQueryWrapper<>();
            dfWrapper.eq(DishFlavor::getDishId, record.getId());
            List<DishFlavor> flavors = dishFlavorService.list(dfWrapper);
            List<String> flavorNames = flavors.stream().map(DishFlavor::getName).collect(Collectors.toList());
            dcf.setFlavornames(flavorNames);

            // 获取DishFlavor值
            List<String> flavorValues = flavors.stream().map(DishFlavor::getValue).collect(Collectors.toList());
            dcf.setFlavorvalues(flavorValues);

            dcf.setDish(record);
            dcfPage.getRecords().add(dcf);
        }

        return Result.success(dcfPage);
    }

    @PostMapping
    public Result<Object> save(@RequestBody CAT dish) {
        dish.setCreateUser("");
        dish.setUpdateUser("");
        dish.setCreateTime(new Date());
        dish.setUpdateTime(new Date());
        dishService.save(dish);
        System.out.println("----------");
        for (DishFlavor dish1 : dish.getFlavors()) {
            dish1.setDishId(dish.getId());
            dish1.setCreateTime(new Date());
            dish1.setUpdateTime(new Date());
            dish1.setCreateUser("");
            dish1.setUpdateUser("");
            dishFlavorService.save(dish1);
        }
        return Result.success();
    }

    @DeleteMapping
    public Result<Object> delete(@RequestParam String ids) {
        dishService.deleteById(ids);
        // 返回成功结果
        return Result.success();
    }

    @PutMapping
    public Result<Object> update(@RequestBody CAT dish) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("dish_id",dish.getId());
        dishFlavorService.remove(queryWrapper);
        dishService.updateById(dish);

        for (DishFlavor dish1 : dish.getFlavors()) {
            dish1.setDishId(dish.getId());
            dish1.setCreateTime(new Date());
            dish1.setUpdateTime(new Date());
            dish1.setCreateUser(dish.getCreateUser());
            dish1.setUpdateUser(dish.getUpdateUser());
            dishFlavorService.save(dish1);
        }
        return Result.success();
    }

    /**
     * 根据id查询详情
     */
    @GetMapping("{id}")
    public Result<Object> findById(@PathVariable Long id){
        Dish dish = dishService.getById(id);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);

        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        log.info("查询单个菜品详情");
        Map<String, Object> map = new HashMap<>();
        map.put("flavors",list);
        map.put("dish", dish);
        return Result.success(map);
    }

    @GetMapping("/list")
    public Result<Object> list(Dish dish){
        List<Dish> list= dishService.listDish(dish);
        return Result.success(list);
    }

    /**
     * 修改菜品状态
     */
    @PostMapping("/status/{status}")
    public Result<Object> updatestuats(@PathVariable Integer status,@PathParam("id") String id) {
        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getId,id);
        Dish one = dishService.getOne(wrapper);
        one.setStatus(status);
        System.out.println("准备进行修改操作");
        dishService.updateStatus(one);
        return Result.success();
    }
}
